<template>
  <view class="add-test">
    <view class="form-item">
      <FormTitle :title="'考试规模'" :type="'scale'"></FormTitle>
      <view class="check-list">
        <view :class="[
            'check-list-item',
            scale.typeId == item.typeId
                ? 'check-list-item-active'
                : '',
        ]" @click="scaleChange(item)" v-for="item in scaleList" :key="item.typeId">{{ item.typeName }}
        </view>
      </view>
    </view>

    <view class="form-item" v-if="scale.typeId">
      <FormTitle :title="'考试类型'" :type="'type'"></FormTitle>
      <view class="check-list">
        <view :class="[
            'check-list-item',
            type.id == item.id ? 'check-list-item-active' : '',
        ]" @click="typeChange(item)" v-for="item in typeList" :key="item.id">{{ item.name }}
        </view>
      </view>
    </view>

    <!--  月考 周考选择考试时间 -->
    <view class="form-item" v-if="type.name == '月考' || type.name == '周考'">
      <FormTitle :title="'考试时间'" :type="'time'"></FormTitle>
      <view class="time-select" :style="{ color: timeInfo.time ? '#333' : '#ccc' }" @click="showChooseTime">
        {{ timeInfo.showTime }}
        <u-icon name="arrow-right"></u-icon>
      </view>
    </view>

    <view :class="['form-item', scale.typeId ? '' : 'disabled']">
      <FormTitle :title="'参与对象'" :type="'user'" :desc="scale.typeId ? '' : '请先选择参与对象'"></FormTitle>
      <view class="join-user" @click="showChooseClass" :style="{ color: curClass.id ? '#333' : '#ccc' }">
        <text>{{ curClass.name ? curClass.name : "请选择" }}</text>
        <u-icon name="arrow-right"></u-icon>
      </view>
    </view>

    <!-- 其他考试  考试名称 -->
    <view class="form-item" v-if="scale.typeName != '班级考试' && type.isOperate">
      <FormTitle :title="'考试名称'" :type="'name'"></FormTitle>
      <view class="name-select" :style="{ color: name.examId ? '#333' : '#ccc' }" @click="showName">
        <text>{{ name.name }}</text>
        <u-icon name="arrow-right"></u-icon>
      </view>
    </view>
    <!-- 班级考试  考试名称 -->
    <view class="form-item" v-if="scale.typeName == '班级考试'">
      <FormTitle :title="'考试名称'" :type="'name'"></FormTitle>
      <view class="num-input" :style="{ color: name.name ? '#333' : '#ccc' }">
        <u-input placeholder="请输入考试名称" style="height: 100%" v-model="name.name" border="bottom" clearable>
        </u-input>
      </view>
    </view>

    <view class="form-item">
      <FormTitle :title="'考试科目'" :type="'course'"></FormTitle>
      <view class="check-list">
        <view :class="[
            'check-list-item',
            course.courseId == item.courseId
                ? 'check-list-item-active'
                : '',
        ]" @click="courseChange(item)" v-for="item in courseLists" :key="item.courseId">
          {{ item.courseName ? item.courseName : "" }}
        </view>
      </view>
    </view>

    <view class="form-item">
      <FormTitle :title="'分数/等级'" :type="'result'"></FormTitle>
      <view class="check-list">
        <view :class="[
            'check-list-item',
            levelInfo.levelId == item.levelId
                ? 'check-list-item-active'
                : '',
        ]" @click="levelChange(item)" v-for="item in levelList" :key="item.levelId">{{ item.levelame }}
        </view>
      </view>
      <view class="num-input" v-if="levelInfo.levelId == 1">
        <u-input placeholder="请输入本次考试卷面总分" type="number" style="height: 100%"
          :disabled="checkInfo.publish || levelInfo.disabled" v-model="levelInfo.num" border="bottom" clearable>
        </u-input>
      </view>
      <view class="level-select" v-if="levelInfo.levelId == 2" :style="{ color: levelInfo.id ? '#333' : '#ccc' }"
        @click="showlevel">
        <view>
          {{ levelInfo.name }}
        </view>
        <u-icon name="arrow-right"></u-icon>
      </view>
    </view>

    <view class="action-btn">
      <view class="reset" @click="reset">重置</view>
      <view class="entry" @click="entry">创建并录入成绩</view>
    </view>

    <!-- 选择考试名称 -->
    <taskName :visible="showNameModal" :postData="postData" @show="showName" @change="nameChange">
    </taskName>

    <!-- 月考选择月份 -->
    <u-datetime-picker :show="showMonth" v-model="month" @confirm="checkMonth" @change="monthChange"
      @cancel="showMonth = false" mode="year-month">
    </u-datetime-picker>

    <!-- 班级列表 -->
    <slice-select key="class" v-if="showClass" :default-checked-key="curClass.id"
      :default-selected-key-list="selectedKeyListClass" :source-type="'class'" :soure-list="classTree"
      @onChecked="onCheckedSliceSelectClass">
    </slice-select>

    <!-- 周考选择周次 -->
    <u-picker :show="showWeek" :columns="[columns]" @cancel="showWeek = false" @confirm="checkWeek">
    </u-picker>

    <!-- 选择等级 -->
    <u-picker :show="showlevelPicker" :columns="[templateList]" @change="levelPickerChange" @confirm="checkLevel"
      keyName="name" @cancel="showlevelPicker = false">
    </u-picker>

    <u-modal :show="sureModal" @confirm="sureOk" @cancel="sureCancel" showCancelButton>
      <p>是否确定提交？</p>
    </u-modal>
  </view>
</template>

<script>
import FormTitle from "./components/form-title.vue"
import sliceSelect from "@/pages/achievement/components/slice-select.vue"
import taskName from "@/pages/achievement/pages/teacher/components/taskName.vue"

import dayjs from "dayjs"
import weekOfYear from "dayjs/plugin/weekOfYear"
dayjs.extend(weekOfYear)

import { getInfoTypeList } from "@/pages/achievement/static/js/getInfoTypeList.js"

import {
  courseList,
  schoolGradeTerm,
  gradeTree,
} from "@/pages/achievement/api/common.js"

import { inputSaveCheck, inputSave } from "@/pages/achievement/api/teacher.js"
	import { mapState } from "vuex"
export default {
  components: {
    FormTitle,
    sliceSelect,
    taskName,
  },
  data() {
    return {
      gradeTerm: {}, // 学年学期
      scale: {}, // 考试规模
      scaleList: [], // 规模列表
      typeList: [], // 类型列表
      gradeTypeList: [],
      classTypeList: [],
      type: {}, // 考试类型
      showNameModal: false,
      postData: {},
      name: {
        name: "请选择考试名称",
        exmaId: "",
      },
      nameList: [],
      courseLists: [], // 科目列表
      course: "", // 考试科目
      curClass: {
        // 参与对象
        name: "请选择",
        id: "",
      },
      showClass: false,
      classTree: [],
      classBaseTree: [],
      selectedKeyListClass: [],
      resultObj: {
        useLevelFlag: "", // 是否启用等级
      },
      showMonth: false,
      showWeek: false,
      timeInfo: {
        showTime: "请选择时间",
        time: "",
      },
      defaultIndex: [],
      columns: [],
      month: Number(new Date()),
      levelList: [
        { levelame: "分数", levelId: 1 },
        { levelame: "等级", levelId: 2 },
      ], // 启用等级时 列表
      showlevelPicker: false,
      levelCheck: {},
      levelInfo: {
        name: "请选择等级",
        id: "",
      },
      templateList: [],
      // 查询上一次的考试计划
      checkInfo: {
        courseList: [],
      },
      sureModal: false,
      sureData: {}
    }
  },
  computed: {
			...mapState(["userInfo"]),
		},
  onShow() {
    // if(this.userInfo.userType === 'P'){
    //             uni.redirectTo({
	// 						url: '/pages/index/index'
	// 					})
    //         }
    this.reset()
  },
  onLoad() {
    this.init()
    this.getGradeTerm()
    this.getGradeTree()
    this.getCourseList()
  },
  methods: {
    async init() {
      const gradeInfo = await getInfoTypeList("年级考试")
      const classInfo = await getInfoTypeList("班级考试")
      //  规模列表
      this.scaleList = [gradeInfo.typeInfo, classInfo.typeInfo]
      // 类型列表
      this.gradeTypeList = [...gradeInfo.infoList]
      this.classTypeList = [...classInfo.infoList]
    },
    async getGradeTerm() {
      const { data } = await schoolGradeTerm()
      this.gradeTerm = data
    },
    async getCourseList() {
      const data = await courseList()
      this.courseLists = data?.data?.list
      this.$store.commit("homework/setCourseList", data?.data?.list)
    },
    //  规模切换时 切换类型列表
    scaleChange(type) {
      console.log(type)
      this.reset()
      this.scale = type
      if (type.typeName == "年级考试") {
        // this.name.name = "请选择考试名称"
        this.typeList = [...this.gradeTypeList]
        this.classTree = this.getTree(this.classBaseTree)
      } else {
        this.name.name = ""
        this.typeList = [...this.classTypeList]
        this.classTree = this.getTree(this.classBaseTree)
      }
    },
    // 选择考试时间
    showChooseTime() {
      if (this.type.name == "月考") {
        this.showMonth = true
      } else if (this.type.name == "周考") {
        this.columns = []
        for (let i = 1; i < 53; i++) {
          this.columns.push(`第${i}周`)
        }
        this.defaultIndex = [dayjs(new Date()).week() - 1]
        console.log(this.defaultIndex)
        this.showWeek = true
      }
    },
    monthChange(value) {
      console.log(value)
      this.month = value?.value
    },
    checkMonth() {
      console.log(this.month)
      this.timeInfo.showTime = dayjs(this.month).format("YYYY年MM月")
      this.timeInfo.time = this.month
      this.showMonth = false
      this.checkSame()
    },
    checkWeek(data) {
      console.log(data)
      this.timeInfo.showTime = data.value[0]
      this.timeInfo.time = data.indexs[0]
      this.showWeek = false

      this.checkSame()
    },
    //  类型切换
    async typeChange(type) {
      console.log(type)
      this.type = { ...type }
      if (this.scale.typeName == "班级考试") {
        this.name.name = ""
      } else {
        this.name = {
          name: "请选择考试名称",
          examId: "",
        }
      }
      this.timeInfo = {
        showTime: "请选择时间",
        time: "",
      }
      this.checkSame()
    },
    //  选择科目
    courseChange(course) {
      this.course = course
      if (this.checkInfo.courseList?.length > 0) {
        for (let item of this.checkInfo.courseList) {
          if (item.courseId == course.courseId) {
            if (item.useLevelFlag) {
              this.levelInfo.levelId = 2
              this.levelInfo.name = item.levelDetail
              this.levelInfo.disabled = true
            } else {
              this.levelInfo.levelId = 1
              this.levelInfo.num = item.fullScore
              this.levelInfo.disabled = true
            }
            break
          } else {
            this.levelInfo.levelId = ""
            this.levelInfo.num = ""
            this.levelInfo.name = ""
            this.levelInfo.disabled = false
          }
        }
      }
    },
    //  选择考试名称
    showName() {
      if (this.scale.typeName == "班级考试") return
      this.showNameModal = true
      this.postData = {
        gradeAndTerm: `${this.gradeTerm.grade},${this.gradeTerm.term}`,

        classId: this.curClass.id,
        // campus: this.selectedKeyListClass[0],
        // period: this.selectedNamsClass[1].split('_')[1],
        // gradeLevel: this.selectedNamsClass[2].split('_')[1],
        type: this.type.id,
      }
    },
    nameChange(data) {
      console.log(data)
      this.showNameModal = false
      this.name = { ...data.item }
      console.log(this.name)
      this.postData = {}
      this.checkSame()
    },
    //  检查该考试是否有创建
    async checkSame() {
      if (this.scale.typeName == "班级考试") return
      let name = ""
      if (this.type.isOperate) {
        name = this.name.name
      } else {
        if (this.type.name === "月考") {
          name = this.timeInfo.showTime + "月考"
        } else if (this.type.name == "周考") {
          name = this.timeInfo.showTime + "周考"
        } else {
          name = this.type.name
        }
      }

      if (!name) return
      if (!this.type.typeName) return
      if (!this.gradeTerm.grade) return
      if (!this.type.id) return
      if (!this.curClass.id) return

      const postData = {
        // campus: this.selectedKeyListClass[0],
        // period: this.selectedNamsClass[1].split('_')[1],
        // gradeLevel: this.selectedNamsClass[2].split('_')[1],
        name: name,
        scope: this.scale.typeName == "年级考试" ? "grade" :
          "class",
        gradeAndTerm: `${this.gradeTerm.grade},${this.gradeTerm.term}`,
        type: this.type.id,
        classId: this.curClass.id,
      }
      const { data } = await inputSaveCheck(postData)
      console.log(data)
      this.checkInfo = data
    },
    //  选择分数等级
    async levelChange(level) {
      if (this.checkInfo?.publish) {
        return uni.showToast({
          icon: "none",
          title: "已发布的成绩不能编辑",
        })
      }
      this.levelInfo = { ...this.levelInfo, ...level }
      this.levelInfo.num = ""
      this.levelInfo.name = ""

      if (this.checkInfo.courseList?.length > 0) {
        for (let item of this.checkInfo.courseList) {
          if (item.courseId == this.course.courseId) {
            if (item.useLevelFlag) {
              console.log(item)
              // this.levelInfo.levelId = 2
              this.levelInfo.name = item.levelDetail
              this.levelInfo.id = item.levelId
              if (this.typeName == "年级考试") {
                this.levelInfo.disabled = true
              }
            } else {
              // this.levelInfo.levelId = 1
              this.levelInfo.num = item.fullScore
              if (this.typeName == "年级考试") {
                this.levelInfo.disabled = true
              }
            }
          }
        }
      }

      if (level.levelId == 2 && !this.templateList?.length) {
        const templateInfo = await getInfoTypeList("等级默认")
        console.log('lllllll',templateInfo)
        this.templateList = templateInfo.infoList
      }
    },
    showlevel() {
      if (this.checkInfo?.publish) {
        return uni.showToast({
          icon: "none",
          title: "已发布的成绩不能编辑",
        })
      }
      if (this.levelInfo.disabled) {
        return uni.showToast({
          icon: "none",
          title: "本科目已有成绩录入，不允许修改，请直接录入",
        })
      }
      this.showlevelPicker = true
    },
    levelPickerChange(value) {
      this.levelCheck = value.value[0]
    },
    checkLevel(item) {
      console.log(item)
      const { value } = item
      const [checked] = value
      this.levelInfo = {
        ...this.levelInfo,
        ...this.levelCheck,
        ...checked,
      }
      this.showlevelPicker = false
    },
    //  选择参与对象
    showChooseClass() {
      this.showClass = true
      if (this.scale.typeId) { }
    },
    // 获取班级树
    getGradeTree() {
      let that = this
      let params = {
        deptType: "class",
        isAuth: true,
      }
      gradeTree(params).then((res) => {
        let { code, data, msg } = res
        if (Number(code) === 0) {
          // let {
          // 	selectedKeyListClass,
          // 	selectedNamsClass,
          // 	curClass
          // } = this.initClassData(data.list)
          this.classBaseTree = data.list
          this.classTree = data.list
          // this.selectedKeyListClass = selectedKeyListClass
          // this.selectedNamsClass = selectedNamsClass
          // this.curClass = curClass
        } else {
          uni.showToast({
            icon: "fail",
            title: msg,
          })
        }
      })
    },
    getTree(list, parent) {
      return list?.map((item) => {
        // const data = {
        // 	title: item.name,
        // 	key: `${item.id}/${item.dataIndex}`,
        // };
        // if (parent?.parentKeys) {
        //   data.parentKeys = parent?.parentKeys.push(parent.key);
        // } else {
        //   data.parentKeys = [parent?.key];
        // }
        // if (parent && parent.id) {
        // 	data.key =
        // 		`${parent.key}_${item.id}/${item.dataIndex}`
        // 	item.key =
        // 		`${parent.key}_${item.id}/${item.dataIndex}`
        // } else {
        // 	item.key = `${item.id}/${item.dataIndex}`
        // }
        const gradeLevel =
          this.scale.typeName == "年级考试" ? "grade" : "class"
        if (item.child?.length > 0 && item.deptType !=
          gradeLevel) {
          // data.checkable = false
          item.children = this.getTree(item.child, item)
          // data.hasChild = true;
        }
        return item
      })
    },
    // 切换班级
    onCheckedSliceSelectClass(sliceSelectData) {
      console.log(sliceSelectData)
      if (sliceSelectData.item) {
        let { selectedKeyList, selectedNams, item } = sliceSelectData
        // this.selectedKeyListClass = selectedKeyList;
        // this.selectedNamsClass = selectedNams;
        this.curClass = item
        // this.filterData.classId = item.id;
      }
      this.checkSame()
      if (sliceSelectData.hide) {
        this.showClass = false
      }
    },
    reset() {
      this.scale = {}
      this.name = {
        name: "请选择考试名称",
        exmaId: "",
      }
      this.type = {}
      this.curClass = {
        // 参与对象
        name: "请选择",
        id: "",
      }

      this.selectedKeyListClass = []
      this.selectedNamsClass = ""
      this.timeInfo = {
        showTime: "请选择时间",
        time: "",
      }
      this.course = ""
      this.month = Number(new Date())
      this.resultObj = {
        useLevelFlag: "", // 是否启用等级
      }
      this.levelInfo = {
        name: "请选择等级",
        id: "",
      }
      this.checkInfo = {
        courseList: [],
      }
    },
    entry() {
      let name = ""
      if (this.scale.typeName == "班级考试" || this.type.isOperate) {
        name = this.name.name
      } else {
        if (this.type.name === "月考") {
          name = this.timeInfo.showTime + "月考"
        } else if (this.type.name == "周考") {
          name = this.timeInfo.showTime + "周考"
        } else {
          name = this.type.name
        }
      }
      let msg = ""
      if (!this.scale.typeId) {
        msg = "请选择考试规模"
      }
      if (!this.type.id) {
        msg = "请选择考试类型"
      }
     
      if (
        (this.type.name == "月考" || this.type.name == "周考") &&
        !this.timeInfo.showTime
      ) {
        msg = "请选择考试时间"
      }
      if (!this.curClass.id) {
        msg = "请选择参与对象"
      }
      if (this.type.isOperate && !this.name.name) {
        msg = "请选择考试名称"
      }
      if (this.scale.typeName == "班级考试" && !this.name.name) {
        msg = "请输入考试名称"
      }
      if (!this.course.courseId) {
        msg = "请选择考试科目"
      }
      if (!this.levelInfo.levelId) {
        msg = "请选择分数/等级"
      }
      console.log("11111111",this.levelInfo)
      if (this.levelInfo.levelId == 1 && !this.levelInfo.num) {
        msg = "请输入科目分数"
      }
      if (this.levelInfo.levelId == 2 && !this.levelInfo.id) {
        msg = "请选择等级"
      }

      if (msg) {
        return uni.showToast({
          icon: "none",
          title: msg,
        })
      }

      const postData = {
        // campus: this.selectedKeyListClass[0],
        // period: this.selectedNamsClass[1].split('_')[1],
        // gradeLevel: this.selectedNamsClass[2].split('_')[1],
        classId: this.curClass.id,
        courseInfo: {
          courseId: this.course.courseId,
          courseName: this.course.courseName,
          fullScore: this.levelInfo.num,
          levelDetail: this.levelInfo.name,
          levelId: this.levelInfo.id,
          useLevelFlag: this.levelInfo.levelId == 2,
        },
        gradeAndTerm: `${this.gradeTerm.grade},${this.gradeTerm.term}`,
        name,
        scope: this.type.typeName == "年级考试" ? "grade" : "class",
        type: this.type.id,
        typeName: this.type.name,
      }
      if (this.checkInfo.examId) {
        postData.examId = this.checkInfo.examId
        this.postAdd(postData)
      } else {
        this.sureModal = true
        this.sureData = postData
      }
    },
    async sureOk() {
      await this.postAdd(this.sureData)
      this.sureCancel()
    },
    sureCancel() {
      this.sureModal = false
      this.sureData = {}
    },

    async postAdd(postData) {
      try {
        const { data } = await inputSave(postData)
        console.log(data)
        uni.showToast({
          icon: "none",
          title: "操作成功",
        })
        uni.redirectTo({
          url: `/pages/achievement/pages/teacher/entry?classCourseId=${data.classCourseId}`,
        })
      } catch (error) {
        console.log(error)
        uni.showToast({
          icon: "none",
          title: error.msg,
        })
      }
    },
  },
}
</script>

<style scoped lang="scss">
.add-test {
  height: 100vh;
  overflow-y: scroll;
  padding: 16rpx 0 200rpx 0;

  .form-item {
    padding: 0 30rpx 0 32rpx;
    margin-bottom: 48rpx;
  }

  .disabled {
    opacity: 0.3;
  }

  .check-list {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  .check-list-item {
    width: 220rpx;
    height: 64rpx;
    background: #f2f4fa;
    border-radius: 8rpx;
    line-height: 64rpx;
    text-align: center;
    color: #999999;
    font-size: 26rpx;
    margin: 0 0 16rpx 14rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

    &:first-child {
      margin-left: 0;
    }

    &:nth-of-type(4n) {
      margin-left: 0;
    }
  }

  .check-list-item-active {
    background: #4174fd;
    color: #fff;
  }

  .join-user {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 2rpx solid #d6d7d9;
    height: 88rpx;
  }

  .num-input,
  .level-select,
  .time-select,
  .name-select {
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    height: 84rpx;
    padding-top: 8rpx;
    border-bottom: 2rpx solid #d6d7d9;
    font-size: 30rpx;
  }

  .level-select {
    padding-left: 18rpx;
  }
}

.action-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 10;
  width: 100%;
  box-sizing: border-box;
  height: 170rpx;
  background: #ffffff;
  box-shadow: 0rpx -2rpx 0rpx 0rpx #e5e5e5;
  // margin-bottom: 68rpx;
  padding: 14rpx 32rpx 80rpx 32rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .reset {
    width: 330rpx;
    height: 72rpx;
    border: 2rpx solid #4174fd;
    border-radius: 38rpx;
    font-size: 30rpx;
    font-weight: 400;
    text-align: center;
    color: #4174fd;
    line-height: 72rpx;
  }

  .entry {
    width: 330rpx;
    height: 72rpx;
    border-radius: 38rpx;
    font-size: 30rpx;
    font-weight: 400;
    text-align: center;
    color: #ffffff;
    line-height: 72rpx;
    background: #4174fd;
  }
}
</style>
